<?php
namespace app\admin\model;

use think\Db;
use think\Model;
use traits\model\SoftDelete;

class Admin extends Base
{
    use SoftDelete;

    // 设置当前模型的数据库连接
    public function role(){
        return $this->hasOne("AuthGroup","id","role_id")->bind(['role_name'=>'title']);
    }
    // 设置当前模型的数据库连接
    public function admin(){
        return $this->hasOne("Admin","id","pid")->bind(['admin_name'=>'username']);
    }
    public function make_token($admin_id){
        $token =  md5(md5(uniqid(microtime(true)).$admin_id.sha1(OmSignAdmin)));
        Db::startTrans();
//        $count = (new AdminToken())->getCount([['admin_id','eq',$admin_id],['overDay_time','gt',time()]]);
//        if($count>0){
//            $res = (new AdminToken())->fieldUpdate('delete_time',time(),"",[['admin_id',"eq",$admin_id]]);
//            if(!$res){
//                Db::rollback();
//                return ['code'=>0,'msg'=>'token删除失败'];
//            }
//        }
        $new = [
            'admin_id'=>$admin_id,
            'token'  =>$token,
            'overDay_time'=>time()+7*86400
        ];
        $res = (new AdminToken())->dataUpdate($new);
        if(!$res){
            Db::rollback();
            return ['code'=>0,'msg'=>'token生成失败'];
        }else{
            Db::commit();
            return ['code'=>1,'msg'=>'token生成成功','token'=>$token];
        }
    }
}